package com.cgx.tablet.beeper.base;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.ColorRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.cgx.tablet.beeper.R;
import com.cgx.tablet.beeper.activity.LoginActivity;
import com.cgx.tablet.beeper.bean.User;
import com.cgx.tablet.beeper.event.FinishActivityEvent;
import com.cgx.tablet.beeper.interfaces.UserDataObserver;
import com.cgx.tablet.beeper.manager.CoreUtils;
import com.cgx.tablet.beeper.utils.SystemBarTintManager;
import com.cgx.tablet.beeper.utils.UserCache;
import com.finddreams.languagelib.MultiLanguageUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.Timer;


/**
 * FrameWork
 * Created by Droven on 2016/9/1.
 */
public class BaseActivity extends AppCompatActivity implements UserDataObserver {

    protected ImageView mLeftIv;
    protected TextView mLeftTv;
    protected TextView mTitleTv;
    protected ImageView mRightIv;
    protected TextView mRightTv;
    protected boolean hasAnim;
    private Dialog loadingDialog;

    private int finishActivityEventTag = -1;
    private Timer timer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UserCache.registerUserDataObserver(this);
        CoreUtils.addAppActivity(this);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguageUtil.attachBaseContext(newBase));
    }

    /**
     * 注册EventBus
     * 一定要在onCreate中调用
     */
    protected void registerEventBus() {
        finishActivityEventTag = 0;
        EventBus.getDefault().register(this);
    }

    protected void registerEventBus(int finishActivityEventTag) {
        this.finishActivityEventTag = finishActivityEventTag;
        EventBus.getDefault().register(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            if (hasAnim)
                overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UserCache.unRegisterUserDataObserver(this);
//        ActivityManager.getInstance().popActivity(this);
        CoreUtils.removeAppActivity(this);
        if (finishActivityEventTag != -1) //销毁EventBus
            EventBus.getDefault().unregister(this);
    }

    /**
     * EventBus方法，结束Activity
     *
     * @param finishActivityEvent 结束Activity事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FinishActivityEvent finishActivityEvent) {
        if (finishActivityEvent.getTag() == finishActivityEventTag) {
            finish();
        }
    }

    /**
     * 初始化ActionBar
     */
    protected void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (null != actionBar) {
            actionBar.setCustomView(R.layout.action_bar_base);
            actionBar.setDisplayShowCustomEnabled(true);
            mLeftIv = actionBar.getCustomView().findViewById(R.id.main_left_iv);
            mLeftTv = actionBar.getCustomView().findViewById(R.id.main_left_tv);
            mTitleTv = actionBar.getCustomView().findViewById(R.id.main_title);
            mRightIv = actionBar.getCustomView().findViewById(R.id.main_right_iv);
            mRightTv = actionBar.getCustomView().findViewById(R.id.main_right_tv);
            mLeftIv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                    if (hasAnim)
                        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
                }
            });
        }
    }

    protected void initActionBar(@StringRes int resId) {
        initActionBar();
        if (mTitleTv != null)
            mTitleTv.setText(resId);
    }

    protected void initActionBar(String title) {
        initActionBar();
        if (mTitleTv != null)
            if (!TextUtils.isEmpty(title))
                mTitleTv.setText(title);
    }

    public void setTitle(@StringRes int resId) {
        if (mTitleTv != null)
            mTitleTv.setText(getResources().getString(resId));
    }

    /**
     * 设置右边图片(资源文件)，必须在调用initActionBar()之后调用，不然报空
     */
    public void setRightImage(int imgId) {
        if (mRightIv != null)
            mRightIv.setImageDrawable(getResources().getDrawable(imgId));
    }

    /**
     * 改状态栏的颜色，布局文件最顶层父控件要加上一下两行代码
     * android:clipToPadding="true"
     * android:fitsSystemWindows="true"
     * 建议在setContentView之前调用
     *
     * @param res color的资源id
     */
    protected void initStatusBar(@ColorRes int res) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarAlpha(50);
            tintManager.setStatusBarTintResource(res);
        }
    }

    /**
     * 键盘弹出时隐藏，键盘隐藏时弹出
     **/
    protected void hideOrShowSoftKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * view为接受键盘的视图，显示键盘
     **/
    protected void showSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 隐藏键盘
     **/
    protected void hideSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 显示加载对话框
     **/
    protected void showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = new Dialog(this, R.style.Translucent_NoTitle);
            loadingDialog.setContentView(R.layout.dialog_loading);
        }
        if (!loadingDialog.isShowing())
            loadingDialog.show();
    }

    /**
     * 隐藏加载对话框
     **/
    protected void hideLoadingDialog() {
        if (loadingDialog != null && loadingDialog.isShowing())
            loadingDialog.dismiss();
    }

    /**
     * 通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls) {
        Intent intent = new Intent();
        startActivity(intent, cls);
    }

    /**
     * 通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, String flag, String msg) {
        Intent intent = new Intent();
        if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(flag)) {
            intent.putExtra(flag, msg);
        }
        startActivity(intent, cls);
    }

    /**
     * 通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, String flag, int id) {
        Intent intent = new Intent();
        intent.putExtra(flag, id);
        startActivity(intent, cls);
    }

    /**
     * 通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, String flag, long id) {
        Intent intent = new Intent();
        intent.putExtra(flag, id);
        startActivity(intent, cls);
    }

    /**
     * 通过Class跳转界面(实体类)
     **/
    protected void startActivity(Class<?> cls, String flag, Object object) {
        Intent intent = new Intent();
        intent.putExtra(flag, (Serializable) object);
        startActivity(intent, cls);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    protected void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent, cls);
    }

    /**
     * 通过Action跳转界面
     **/
    protected void startActivity(String action) {
        startActivity(action, null);
    }

    /**
     * 含有Bundle通过Action跳转界面
     **/
    protected void startActivity(String action, Bundle bundle) {
        Intent intent = new Intent();
        intent.setAction(action);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        if (hasAnim)
            overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    /**
     * 真正的跳转
     **/
    protected void startActivity(Intent intent, Class<?> cls) {
        intent.setClass(this, cls);
        startActivity(intent);
        if (hasAnim)
            overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    protected void startActivityResult(Intent intent, int flag) {
        super.startActivityForResult(intent, flag);
        if (hasAnim)
            overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    /**
     * 检测和请求运行时权限，不建议一次检测多个权限
     *
     * @param permission    要请求的权限
     * @param permissionMsg 需要的提示信息
     * @param requestCode   请求码以标记对应的权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    protected void requestPermission(@StringRes int permissionMsg, final int requestCode, final String... permission) {
        if (ContextCompat.checkSelfPermission(this, permission[0]) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission[0])) {
                new AlertDialog.Builder(this)
                        .setMessage(permissionMsg)
                        .setPositiveButton(R.string.str_confirm, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(BaseActivity.this, permission, requestCode);
                            }
                        }).show();
            } else {
                ActivityCompat.requestPermissions(this, permission, requestCode);
            }
        } else {
            permissionResult(requestCode, true);
        }
    }

    //子Activity重新这个方法即返回权限结果
    protected void permissionResult(int requestCode, boolean hadPermission) {
    }

    //系统返回的权限结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            permissionResult(requestCode, true);
        } else if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
            permissionResult(requestCode, false);
            startSetPermission();
        }
    }

    //启动设置界面让用户手动设置
    private void startSetPermission() {
        Uri packageURI = Uri.parse("package:" + getPackageName());
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
        startActivity(intent);
    }

    @Override
    public void onUserDataChanged(User user) {
        if (user == null) {
            finish();
            startActivity(LoginActivity.class);
        }
    }


}
